<template>
	<uv-popup ref="popupBox" mode="bottom" :round="10" @maskClick="closeFunc">
		<view class="title">提交尾款凭证</view>
		<uv-alert center v-if="tpisShow" type="warning" description="已超出优惠权限，需客户总监审批"></uv-alert>
		<scroll-view class="scroll-view" scroll-y>
			<view class="uv-form-box">
				<uv-form labelPosition="top" :model="formData" :rules="rules" ref="form" labelWidth="auto">
					<uv-form-item label="实付尾款金额" prop="amount_collected" required>
						<uv-input @input="inputBlurFuncamount_collected" type="digit" placeholder="请输入实付尾款金额" v-model="formData.amount_collected"></uv-input>
					</uv-form-item>
					<uv-form-item label="结算优惠金额" prop="settlement_discount_amount" required>
						<uv-input
							type="digit"
							placeholder="请输入结算优惠金额"
							v-model="formData.settlement_discount_amount"
							@input="inputBlurFuncsettlement_discount_amount"
						></uv-input>
					</uv-form-item>
					<uv-form-item label="待付款金额" prop="unpaid_amount" required>
						<uv-input disabled type="digit" placeholder="请输入待付款金额" v-model="formData.unpaid_amount"></uv-input>
					</uv-form-item>
					<uv-form-item label="最终结算金额" prop="final_settlement_amount" required>
						<uv-input disabled type="digit" placeholder="请输入待付款金额" v-model="formData.final_settlement_amount"></uv-input>
					</uv-form-item>
					<uv-form-item label="最终利润金额" prop="final_profit_amount" required>
						<uv-input disabled type="digit" placeholder="请输入最终利润金额" v-model="formData.final_profit_amount"></uv-input>
					</uv-form-item>
					<uv-form-item label="收款账户" prop="receiving_account_id" @click="selectReceivingAccount" required>
						<uv-input readonly placeholder="请选择" v-model="formData.receiving_account_id"></uv-input>
					</uv-form-item>
					<uv-form-item label="结算完成日期" prop="settlement_completion_date" @click="selectDate('settlement_completion_date')" required>
						<uv-input readonly placeholder="请选择" v-model="formData.settlement_completion_date"></uv-input>
					</uv-form-item>
					<uv-form-item label="质保截止日期" prop="warranty_deadline_date" @click="selectDate('warranty_deadline_date')" required>
						<uv-input readonly placeholder="请选择" v-model="formData.warranty_deadline_date"></uv-input>
					</uv-form-item>
					<uv-form-item label="支付凭证 (.jpg,.png,.gif)" prop="payment_voucher" labelPosition="left" required>
						<view class="file-box">
							<uv-button
								type="primary"
								text="点击上传"
								@click="uploadFunc"
								customTextStyle="font-weight: 400;font-size: 24rpx;color: #FFFFFF;"
								customStyle="width: 170rpx;height: 60rpx;background: #3B75FF;border-radius: 16rpx;"
							></uv-button>
						</view>
					</uv-form-item>
					<view class="file-list">
						<view class="file-media" v-for="(item, index) in formData.payment_voucher" :key="index">
							<view class="del-icon" @click.stop="delFile(index, 'payment_voucher')">
								<uv-icon name="trash-fill" size="18" color="#ffffff"></uv-icon>
							</view>
							<image mode="aspectFill" :src="item.tempFilePath" class="media-item"></image>
						</view>
					</view>
					<uv-form-item label="备注" prop="remark">
						<uv-textarea height="100" v-model="formData.remark" placeholder="请输入内容"></uv-textarea>
					</uv-form-item>
				</uv-form>
			</view>
		</scroll-view>
		<view class="btn-box">
			<uv-button
				@click="closeFunc"
				text="取 消"
				customTextStyle="font-weight: 400;font-size: 28rpx;color: #8F8F8F;"
				customStyle="width: 180rpx;height: 80rpx;background: #FFFFFF;border-radius: 16rpx;border: 2rpx solid #E3E3E3;margin-bottom:20rpx;"
			></uv-button>
			<uv-button
				@click="formSubmit"
				type="primary"
				text="提 交"
				customTextStyle="font-weight: 400;font-size: 28rpx;color: #FFFFFF;"
				customStyle="width: 500rpx;height: 80rpx;background: #3B75FF;border-radius: 16rpx;margin-bottom:20rpx;"
			></uv-button>
		</view>
	</uv-popup>
	<!-- 账户列表 -->
	<uv-picker title="账户列表" ref="zhPicker" :columns="zhPolumns" @confirm="zhConfirm" keyName="account_name"></uv-picker>
	<!-- 日期选择 -->
	<uv-datetime-picker :minDate="minDate" :formatter="formatter" v-model="dateTimeVal" ref="datetimePicker" mode="date" @confirm="dateConfirm"></uv-datetime-picker>
</template>

<script setup>
import { computed, watch, onMounted, getCurrentInstance, ref, defineEmits, nextTick } from 'vue';
const { proxy: that } = getCurrentInstance();
let props = defineProps({
	show: {
		type: Boolean,
		default: () => {
			return false;
		}
	},
	dataObj: {
		type: Object,
		default: () => {
			return {};
		}
	},
	dkData: {
		default: () => {
			return {};
		}
	},
	zjData: {
		default: () => {
			return {};
		}
	},
	jsdData: {
		default: () => {
			return {};
		}
	},
	signing_company_data: {
		default: () => {
			return {};
		}
	}
});
let tpisShow = ref(false);
let dateTimeVal = ref('');
let dateType = ref('');
let minDate = ref(new Date().getTime());
// 账户列表
let zhPolumns = ref([]);
// 表单数据
let formData = ref({
	amount_collected: '',
	settlement_discount_amount: '',
	final_settlement_amount: '',
	unpaid_amount: '',
	final_profit_amount: '',
	receiving_account_id: '',
	receiving_account_data: '',
	settlement_completion_date: '',
	warranty_deadline_date: '',
	payment_voucher: [],
	remark: ''
});
// 表单规则
let rules = ref({
	amount_collected: {
		required: true,
		message: '请输入预付款金额',
		trigger: ['blur', 'change']
	},
	settlement_discount_amount: {
		required: true,
		message: '请输入结算金额',
		trigger: ['blur', 'change']
	},
	final_settlement_amount: {
		required: true,
		message: '请输入最终结算金额',
		trigger: ['blur', 'change']
	},
	unpaid_amount: [
		{
			asyncValidator: (rule, value, callback) => {
				console.log(value, '待支付');
				if (!value) {
					callback(new Error('请输入待付款金额'));
				} else {
					// 如果校验通过，也要执行callback()回调
					callback();
				}
			},
			trigger: ['blur', 'change']
			// 如果是异步校验，无需写message属性，错误的信息通过Error抛出即可
			// message: 'xxx'
		}
	],
	final_profit_amount: {
		required: true,
		message: '请输入最终利润金额',
		trigger: ['blur', 'change']
	},
	settlement_completion_date: {
		required: true,
		message: '请选择结算完成日期',
		trigger: ['blur', 'change']
	},
	warranty_deadline_date: {
		required: true,
		message: '请选择质保截止日期',
		trigger: ['blur', 'change']
	},
	receiving_account_id: {
		required: true,
		message: '请选择收款账户',
		trigger: ['blur', 'change']
	},
	payment_voucher: [
		{
			asyncValidator: (rule, value, callback) => {
				if (!value.length) {
					callback(new Error('请上传支付凭证'));
				} else {
					// 如果校验通过，也要执行callback()回调
					callback();
				}
			}
			// 如果是异步校验，无需写message属性，错误的信息通过Error抛出即可
			// message: 'xxx'
		}
	]
});

onMounted(() => {
	// that.$refs.popupBox.open();
	// getCompanyList();
});

watch(
	() => props.show,
	(newValue, oldValue) => {
		console.log(newValue, oldValue, '值变化');
		if (props.show) {
			getCompanyList();
			let jsdData = props.jsdData;
			let signing_company_data = props.signing_company_data;
			let unpaid_amount = 0; //待付款金额
			let final_settlement_amount = 0; //最终结算总额
			let final_profit_amount = 0; //最终利润
			// 待付款金额
			unpaid_amount = Number(jsdData.settlement_amount) - Number(jsdData.paid_amount);
			unpaid_amount = ((unpaid_amount * 100) / 100).toFixed(2);
			formData.value.unpaid_amount = unpaid_amount;
			console.log(unpaid_amount, '待付款金额（初步计算）');
			// 最终结算总额
			final_settlement_amount = jsdData.settlement_amount;
			console.log(final_settlement_amount, '最终结算总额（初步计算）');
			formData.value.final_settlement_amount = final_settlement_amount;
			// 最终利润
			final_profit_amount = Number(final_settlement_amount) - Number(jsdData.settlement_cost_amount);
			final_profit_amount = ((final_profit_amount * 100) / 100).toFixed(2);
			formData.value.final_profit_amount = final_profit_amount;
			console.log(final_profit_amount, '最终利润（初步计算）');

			// 收款账户
			formData.value.receiving_account_id = signing_company_data.signing_company_name;
			formData.value.receiving_account_data = {
				id: signing_company_data.signing_company_id,
				account_name: signing_company_data.signing_company_name
			};

			that.$refs.popupBox.open();
		} else {
			formData.value = {
				amount_collected: '',
				settlement_discount_amount: '',
				final_settlement_amount: '',
				unpaid_amount: '',
				final_profit_amount: '',
				receiving_account_id: '',
				receiving_account_data: '',
				settlement_completion_date: '',
				warranty_deadline_date: '',
				payment_voucher: [],
				remark: ''
			};
			that.$refs.form.clearValidate();
			that.$refs.popupBox.close();
		}
	}
);
const emit = defineEmits(['close', 'onSuccess']);

const closeFunc = () => {
	emit('close', false);
};
// //结算优惠金额
const inputBlurFuncsettlement_discount_amount = (e) => {
	console.log(e);
	// 获取输入值
	let value = e
		.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
		.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
		.replace(/^(-)*(\d+)\.(\d{0,2}).*$/, '$1$2.$3'); // 只能输入两个小数
	// 更新数据绑定的值
	formData.value.settlement_discount_amount = '';
	nextTickFunc(value,'settlement_discount_amount');
};
// 实付尾款输入
const inputBlurFuncamount_collected = (e) => {
	console.log(e);
	// 获取输入值
	let value = e
		.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
		.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
		.replace(/^(-)*(\d+)\.(\d{0,2}).*$/, '$1$2.$3'); // 只能输入两个小数
	// 更新数据绑定的值
	formData.value.amount_collected = '';
	nextTickFunc(value,'amount_collected');
};
// input输入nextTick
const nextTickFunc = (value,type) => {
	console.log(value,type,"--------------------")
	nextTick(() => {
		formData.value[type] = value;
		let amount_collected = formData.value.amount_collected || 0; //实付尾款金额
		let settlement_discount_amount = formData.value.settlement_discount_amount || 0; //结算优惠金额

		let jsdData = props.jsdData;
		let settlement_discount_ratio = uni.getStorageSync('userInfo').settlement_discount_ratio; //最大优惠权限
		let unpaid_amount = formData.value.unpaid_amount || 0; //待付款金额
		let final_settlement_amount = formData.value.final_settlement_amount || 0; //最终结算总额
		let final_profit_amount = formData.value.final_profit_amount || 0; //最终利润
		// 待付款金额
		let unpaid_amountVal = Number(amount_collected) + Number(settlement_discount_amount) + Number(jsdData.paid_amount);
		unpaid_amount = Number(jsdData.settlement_amount) - Number(unpaid_amountVal);
		unpaid_amount = ((unpaid_amount * 100) / 100).toFixed(2);
		formData.value.unpaid_amount = unpaid_amount;
		console.log(unpaid_amount, '待付款金额');
		// 最终结算总额
		final_settlement_amount = Number(jsdData.settlement_amount) - Number(settlement_discount_amount);
		final_settlement_amount = ((final_settlement_amount * 100) / 100).toFixed(2);
		formData.value.final_settlement_amount = final_settlement_amount;
		console.log(final_settlement_amount, '最终结算总额');
		// 最终利润
		final_profit_amount = Number(final_settlement_amount) - Number(jsdData.settlement_cost_amount);
		final_profit_amount = ((final_profit_amount * 100) / 100).toFixed(2);
		formData.value.final_profit_amount = final_profit_amount;
		console.log(final_profit_amount, '最终利润');
		// 是否超出优惠权限
		if (Number(settlement_discount_amount) > Number(settlement_discount_ratio)) {
			tpisShow.value = true;
		} else {
			tpisShow.value = false;
		}
		console.log(tpisShow.value, '是否超出优惠权限');
	});
};
// 上传文件
const uploadFunc = () => {
	uni.chooseMedia({
		mediaType: ['image'], //, 'video'
		sourceType: ['album', 'camera'],
		count: 1,
		success(res) {
			console.log(res.tempFiles);
			res.tempFiles.map((item) => {
				formData.value.payment_voucher = [item];
				that.$refs.form.validateField('payment_voucher');
			});
		}
	});
};
// 删除文件
const delFile = (index) => {
	formData.value.payment_voucher.splice(index, 1);
	that.$refs.form.validateField('payment_voucher');
};

// 账户列表
const getCompanyList = () => {
	zhPolumns.value = [];
	that.$Api
		.getCompanyList({
			page: 1,
			num: 9999,
			account_type: 1
		})
		.then((res) => {
			console.log(res, '账户列表');
			if (res.code == 200) {
				zhPolumns.value.push(res.data.list);
			}
		});
};
// 选择账户
const zhConfirm = (e) => {
	console.log(e);
	formData.value.receiving_account_id = e.value[0].account_name;
	formData.value.receiving_account_data = e.value[0];
	that.$refs.form.validateField('receiving_account_id');
};
const selectReceivingAccount = () => {
	that.$refs.zhPicker.open();
};
const selectDate = (type) => {
	dateType.value = type;
	const now = new Date().getTime() + 86400000;
	switch (type) {
		case 'settlement_completion_date':
			dateTimeVal.value = formData.value.settlement_completion_date ? dateFormatToTimestamp(formData.value.settlement_completion_date) : now;
			minDate.value = now;
			break;
		case 'warranty_deadline_date':
			dateTimeVal.value = formData.value.warranty_deadline_date ? dateFormatToTimestamp(formData.value.warranty_deadline_date) : now;
			minDate.value = now;
			break;
		default:
	}
	that.$refs.datetimePicker.open();
};
// 日期选择
const dateConfirm = (e) => {
	console.log(e, '选择日期');
	switch (dateType.value) {
		case 'settlement_completion_date':
			formData.value.settlement_completion_date = timestampToDateFormat(e.value);
			break;
		case 'warranty_deadline_date':
			formData.value.warranty_deadline_date = timestampToDateFormat(e.value);
			break;
		default:
	}
	that.$refs.form.validateField(dateType.value);
};

function dateFormatToTimestamp(date) {
	// const date = new Date(data); // 获取当前日期对象
	// const timestamp = date.getTime(); // 获取时间戳
	console.log(date);
	return Date.parse(date);
}

function timestampToDateFormat(timestamp) {
	const dateObj = new Date(timestamp); // 创建Date对象
	const year = String(dateObj.getFullYear()); // 获取年份
	const month = String(dateObj.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
	const day = String(dateObj.getDate()).padStart(2, '0'); // 获取日期，并补零

	return year + '-' + month + '-' + day; // 返回转换后的日期格式
}
const formatter = (type, value) => {
	if (type === 'year') {
		return `${value}年`;
	}
	if (type === 'month') {
		return `${value}月`;
	}
	if (type === 'day') {
		return `${value}日`;
	}
	return value;
};
// 表单提交
const formSubmit = () => {
	let data = formData.value;
	let dataObj = props.dataObj;
	console.log(data, '表单数据', dataObj);
	that.$refs.form
		.validate()
		.then((res) => {
			uni.showLoading({
				mask: true,
				title: '文件上传中...'
			});
			that.$upload(data.payment_voucher).then((res) => {
				console.log(1111, res);
				uni.hideLoading();

				uni.showLoading({
					mask: true,
					title: '信息提交中...'
				});
				that.$Api
					.wxFinalPaymentCollection({
						payment_voucher: res.arrResult,
						project_id: dataObj.id,
						receiving_account_id: data.receiving_account_data.id,
						receiving_account_name: data.receiving_account_id,
						remark: data.remark,
						amount_collected: data.amount_collected,
						settlement_discount_amount: data.settlement_discount_amount,
						final_settlement_amount: data.final_settlement_amount,
						unpaid_amount: data.unpaid_amount,
						final_profit_amount: data.final_profit_amount,
						settlement_completion_date: data.settlement_completion_date,
						warranty_deadline_date: data.warranty_deadline_date
					})
					.then((res) => {
						console.log(res, '提交尾款凭证');
						uni.hideLoading();
						if (res.code == 200) {
							emit('onSuccess', true);
						}
						uni.showToast({
							title: res.code == 200 ? '操作成功' : res.message,
							icon: res.code == 200 ? 'success' : 'error'
						});
					})
					.catch((err) => {
						uni.hideLoading();
					});
			});
		})
		.catch((errors) => {});
};
// const statusText = computed(() => {

// });
</script>

<style lang="scss" scoped>
.title {
	font-size: 32rpx;
	width: 100%;
	line-height: 100rpx;
	text-align: center;
}

.btn-box {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	box-sizing: border-box;
	margin-top: 30rpx;
}

.scroll-view {
	width: 100%;
	max-height: 50vh;
	background-color: #fff;

	// padding: 0 30rpx;
	// box-sizing: border-box;
	.uv-form-box {
		padding: 0 30rpx !important;
	}

	.file-box {
		width: 100%;
		display: flex;
		flex-direction: row-reverse;
	}

	.file-list {
		width: 100%;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		.file-item {
			display: flex;
			justify-content: space-between;
			margin-top: 10rpx;
			margin-left: 10rpx;
			padding: 10rpx;
			background-color: #f8f8f8;
			width: 90%;

			.file-name {
				font-size: 24rpx;
				overflow: hidden;
				/* 确保溢出文本会被隐藏 */
				white-space: nowrap;
				/* 确保文本在一行内显示 */
				text-overflow: ellipsis;
				/* 使用省略号显示文本溢出的部分 */
				width: 80%;
			}
		}

		.file-media {
			width: 150rpx;
			height: 150rpx;
			margin: 0 27rpx 22rpx 0;
			overflow: hidden;
			border-radius: 10rpx;
			position: relative;

			&:nth-child(4n) {
				margin-right: 0;
			}

			.media-item {
				width: 100%;
				height: 100%;
			}

			.icon-box {
				position: absolute;
				z-index: 1;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				background-color: rgba(0, 0, 0, 0.6);
				width: 70rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
			}

			.del-icon {
				width: 60rpx;
				height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				right: 10rpx;
				top: 10rpx;
				z-index: 1;
				background-color: rgba(0, 0, 0, 0.6);
				border-radius: 10rpx;
			}
		}
	}
}
</style>
